<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\controller;


use app\api\logic\UserLogic;
use app\api\validate\PasswordValidate;
use app\api\validate\SetUserInfoValidate;
use app\api\validate\UserValidate;
use app\common\service\ConfigService;
use think\facade\Db;


/**
 * 用户控制器
 * Class UserController
 * @package app\api\controller
 */
class UserController extends BaseApiController
{
    public array $notNeedLogin = ['resetPassword'];


    /**
     * @notes 获取个人中心
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 段誉
     * @date 2022/9/16 18:19
     */
    public function center()
    {

        $data = UserLogic::center($this->userInfo);
        return $this->success('', $data);
    }


    /**
     * @notes 获取个人信息
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/20 19:46
     */
    public function info()
    {
        $result = UserLogic::info($this->userId);
        return $this->data($result);
    }

//    获取团队成员
    public function groupUser()
    {
        $result = UserLogic::groupUser($this->userInfo['group_id']);
        return $this->data($result);
    }

    //获取团员信息

    public function groupInfo()
    {
        $result = UserLogic::groupInfo($this->userInfo['group_id']);
        return $this->data($result);
    }

    public function groupUserEdit()
    {
        if(!$this->userInfo['role_id']>1){
            return $this->fail('无权限');
        }
        $params = (new UserValidate())->post()->goCheck('groupUserEdit');
        $userInfo = UserLogic::info($params['id']);

        //只能修改自己团队的成员信息
        if ($userInfo['group_id'] != $this->userInfo['group_id']) {
            return $this->fail('无权限');
        }

        $result = UserLogic::groupUserEdit($params);
        if (true === $result) {
            return $this->success('修改成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    public function groupLeader()
    {
        $groupId = $this->userInfo['group_id'];
        $result = UserLogic::groupLeader($groupId);
        return $this->data($result);
    }

    public function buyCard()
    {
        $params = $this->request->param();
        $params['user_id'] = $this->userId;

        $result = UserLogic::buyCard($this->userInfo, $params);
        if (true === $result) {
            return $this->success('购买成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    /**
     * 新卡配额
     * @return \think\response\Json
     */
    public function buyCardLog()
    {
        $params['user_id'] = $this->userId;
        $result = UserLogic::buyCardLog($this->userInfo);
        return $this->data($result);
    }


    /**
     * @notes 重置密码
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/16 18:06
     */
    public function resetPassword()
    {
        $params = (new PasswordValidate())->post()->goCheck('resetPassword');
        $result = UserLogic::resetPassword($params);
        if (true === $result) {
            return $this->success('操作成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    public function changeSecurePassword()
    {
        try {
            // GET请求处理发送邮件
            if ($this->request->isGet()) {

                $email = $this->userInfo['email'];
                if (empty($email)) {
                    return $this->fail('用户邮箱不存在');
                }

                $userId = $this->userId;

                // 检查是否频繁发送
                if (cache('secure_password_change_' . $userId)) {
                    return $this->fail('请勿频繁发送邮件，请5分钟后再试');
                }

                // 生成6位随机验证码
                $code = sprintf('%06d', random_int(0, 999999));

                // 缓存验证码，有效期5分钟
                cache('secure_password_code_' . $userId, $code, 300);
                // 设置发送标记，防止频繁发送
                cache('secure_password_change_' . $userId, true, 300);

                try {
                    $title = ConfigService::get('email', 'secure_title');
                    $content = ConfigService::get('email', 'secure_content');
                    $content = str_replace('{code}', $code, $content);
                    send_mail($email, $title, $content);
                    return $this->success('邮件已发送，请查收');
                } catch (Exception $e) {
                    // 记录详细的错误信息

                    // 清除缓存
                    cache('secure_password_code_' . $userId, null);
                    cache('secure_password_change_' . $userId, null);

                    return $this->fail('邮件发送失败，请检查邮件服务器配置或联系管理员');
                }
            }

            // POST请求处理验证码验证和密码修改
            if ($this->request->isPost()) {
                $params = $this->request->post();

                // 验证参数
                $validate = validate([
                    'code' => 'require|length:6',
                    'password' => 'require|length:6,20',
                    'password_confirm' => 'require|confirm:password'
                ]);

                if (!$validate->check($params)) {
                    return $this->fail($validate->getError());
                }

                // 验证验证码
                $cached_code = cache('secure_password_code_' . $this->userId);
                if (!$cached_code || $cached_code != $params['code']) {
                    return $this->fail('验证码错误或已过期');
                }

                // 更新安全密码
                $result = UserLogic::changeSecurePassword($params, $this->userId);
                if (!$result) {
                    return $this->fail('修改失败，请重试');
                }

                // 清除验证码缓存
                cache('secure_password_code_' . $this->userId, null);
                cache('secure_password_change_' . $this->userId, null);

                return $this->success('安全密码修改成功');
            }

            return $this->fail('非法请求');

        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }


    /**
     * @notes 修改密码
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/20 19:16
     */
    public function changePassword()
    {
        $params = (new PasswordValidate())->post()->goCheck('changePassword');
        $result = UserLogic::changePassword($params, $this->userId);
        if (true === $result) {
            return $this->success('操作成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }


    /**
     * @notes 获取小程序手机号
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 16:46
     */
    public function getMobileByMnp()
    {
        $params = (new UserValidate())->post()->goCheck('getMobileByMnp');
        $params['user_id'] = $this->userId;
        $result = UserLogic::getMobileByMnp($params);
        if ($result === false) {
            return $this->fail(UserLogic::getError());
        }
        return $this->success('绑定成功', [], 1, 1);
    }


    /**
     * @notes 编辑用户信息
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 17:01
     */
    public function setInfo()
    {
        $params = (new SetUserInfoValidate())->post()->goCheck(null, ['id' => $this->userId]);
        $result = UserLogic::setInfo($this->userId, $params);
        if (false === $result) {
            return $this->fail(UserLogic::getError());
        }
        return $this->success('操作成功', [], 1, 1);
    }


    /**
     * @notes 绑定/变更 手机号
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 17:29
     */
    public function bindMobile()
    {
        $params = (new UserValidate())->post()->goCheck('bindMobile');
        $params['user_id'] = $this->userId;
        $result = UserLogic::bindMobile($params);
        if ($result) {
            return $this->success('绑定成功', [], 1, 1);
        }
        return $this->fail(UserLogic::getError());
    }

    public function notis()
    {
        $params['user_id'] = $this->userId;
        $params['group_id'] = $this->userInfo['group_id'];
        $id = $this->request->post('id/d');

        if ($id > 0) {
            $params['id'] = $id;
            $result = Db::name('userNotis')->where($params)->update([
                'is_read' => 1,
                'update_time' => time(),
            ]);
            if ($result) {
                return $this->success('标记成功', [], 1, 1);
            } else {
                return $this->fail('标记失败');
            }
        }
        $list = Db::name('userNotis')->where(['group_id'=>$params['group_id']])
            ->order('id desc')
            ->select()->toArray();
        return $this->success('获取成功', $list, 1, 1);
    }

    public function setNotis()
    {
        $where['group_id'] = $this->userInfo['group_id'];
        if ($this->request->isPost()) {
            $low_balance = $this->request->post('low_balance/f');
            $low_balance_enable = $this->request->post('low_balance_enable/d');

            // 定义要更新或插入的数据
            $data = [
                'user_id'=> $this->userId,
                'group_id'=> $this->userInfo['group_id'],
                'update_time' => time(),
            ];

            if($low_balance_enable !== null){
                $data['low_balance_enable'] = $low_balance_enable;
            }
            if($low_balance !== null){
                $data['low_balance'] = $low_balance;
            }
            // 查找记录
            $record = Db::name('userNotisSetting')->where($where)->find();
            if ($record) {
                // 更新记录
                $result = Db::name('userNotisSetting')->where($where)->update($data);
            } else {
                // 插入记录
                $result = Db::name('userNotisSetting')->insert($data);
            }

            if ($result) {
                return $this->success('设置成功', [], 1, 1);
            } else {
                return $this->fail('设置失败');
            }
        }
        $list = Db::name('userNotisSetting')->where($where)
            ->field('low_balance,low_balance_enable')
            ->findOrEmpty();

        return $this->success('获取成功', $list??[], 1, 1);
    }



}
